<?php

namespace App\Http\Model\Origami;

use App\Http\Model\Base;
use Illuminate\Support\Facades\DB;

class OrigamiTopics extends Base
{
    /**
     * 表名字
     *
     * @var string
     */
    public $table = 'origami_topics';

    /**
     * @var bool
     */
    public $timestamps = true;

    /**
     * 模型日期列的存储格式。
     *
     * @var string
     */
    protected $dateFormat = 'U';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['id', 'type_id', 'content', 'created_at', 'updated_at'];

    /**
     * 构造函数
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 随机获取一条文案
     *
     * @param int $typeId 类型id
     * @return string
     */
    public function randOneTopic(int $typeId): string
    {
        $table = env('DB_PREFIX', 'zb_') . $this->table;
        $sql = 'SELECT content
FROM ' . $table . ' AS t1 
JOIN (SELECT ROUND( RAND () * ((SELECT MAX(id) FROM ' . $table . ' where type_id=' . $typeId . ')-(SELECT MIN(id) FROM ' . $table . ' where type_id=' . $typeId . '))+(SELECT MIN(id) FROM ' . $table . ' where type_id=' . $typeId . ')) AS id) AS t2
WHERE t1.id >= t2.id and t1.type_id=' . $typeId . '
LIMIT 1';
        $query = DB::select($sql);
        return $query ? strval($query[0]->content) : '';
    }

    /**
     * 添加折纸
     * @param $data
     * @return bool
     */
    public function addTopic($data){
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $res = DB::table($this->table)->insert($data);
        return $res;
    }

    /**
     * 编辑折纸
     * @param $data
     * @return int
     */
    public function updateTopic($data){
        $id = $data['id'];
        $data['updated_at'] = time();
        unset($data['id']);
        $res = DB::table($this->table)->where('id',$id)->update($data);
        return $res;
    }

    /**
     * 删除折纸
     * @param $id
     * @return int
     */
    public function delTopic($id){
        return DB::table($this->table)->where('id',$id)->delete();
    }
}
